package com.efounder.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import androidx.core.graphics.drawable.DrawableCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.chat.model.TabMenuClickEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilemall.R;
import com.efounder.util.ImageLoaderUtil;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.widget.QuickAction;
import com.efounder.widget.QuickActionGrid;
import com.efounder.widget.QuickActionWidget;
import com.pansoft.resmanager.ResFileManager;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

/**
 * 扩展底部菜单栏   超过5项时 跳转至更多功能界面
 *
 * @author long 2015-1-30 11:25:57
 */
public class MallTabBar extends LinearLayout {

    private static final String TAG = "TabBarNew";
    private static final String CAPTION = "caption";
    private static final String SELECTEDICON = "selectedIcon";
    private static final String NORMALICON = "normalIcon";
    public static final int MORE_BTN = 1000;/**更多按钮ID 标示号*/
    /**
     * 底部菜单超过6项时的默认值  超过6项时 第五项为弹出框按钮
     */
    public static int BOTTOM_ITEM = 4;
    /**
     * 底部菜单最多
     */
    public static int MAX_BOTTOM_ITEM = 5;
    /**
     * 底部菜单最多数5 +1用于限制底部展出菜单数
     */
    public static int MAX_BOTTOM_ITEMS = MAX_BOTTOM_ITEM + 1;
    private final Context mContext;
    public static int mCurrentTabIndex;

    private QuickActionWidget mGrid;// 快捷栏控件

    /**
     * 记录菜单个数
     */
    private int mTabCount;
    /**
     * 底部菜单宽度
     */
    private int mTabWidth;
    private com.efounder.widget.TabBarNew.OnCurrentTabChangedListener mTabChangedListener;


    private List<EFImage> imageList = new ArrayList<EFImage>();
    private List<TextView> textList = new ArrayList<TextView>();
    private List<StubObject> espMenuList;
    private List<Bitmap> bitmapList;
    private List<Bitmap> bitmap_pressList;

    private List<Object> menuListTemp;//更多菜单
    //记录按钮的id，方便其他类控制tabbar的选择
    private String[] menuArray;

    public String[] getMenuArray() {
        return menuArray;
    }

    public void setMenuArray(String[] menuArray) {
        this.menuArray = menuArray;
    }

    /**
     * TabBar被点击的次数
     */
    private int clickCount;

    Context context;

    private int largePosition = -1;//图标变大的位置
    private boolean hasLargerImange = false;//是否具有大图标

    public MallTabBar(Context context, List<StubObject> espMenuList) {
        super(context);
        this.context = context;
        this.espMenuList = espMenuList;
        bitmapList = new ArrayList<Bitmap>();
        bitmap_pressList = new ArrayList<Bitmap>();
        this.mContext = context;
        setWillNotDraw(false); // 重要!!!
        mCurrentTabIndex = -1;
        mTabCount = 0;
        init();


    }

    public void init() {
        this.setOrientation(LinearLayout.VERTICAL);
        this.setPadding(0, 0, 0, 0);

        int j = 0;
        menuArray = new String[espMenuList.size()];
        for (int i = 0; i < espMenuList.size(); i++) {

            //权限判断
            StubObject soObject = (StubObject) espMenuList.get(i);

            if (!com.efounder.util.SecurityManager.checkGNQXWithStub(context, soObject)) {
                espMenuList.remove(i - j);
                j++;
            }

            String id = soObject.getObject("id", "").toString();
            menuArray[i] = id;

            String normalIcon = soObject.getObject(NORMALICON, "").toString();
            System.out.println(normalIcon);
            normalIcon = ResFileManager.IMAGE_DIR + "/" + normalIcon;

            File file = new File(normalIcon);
            if (file.exists()) {
                //Bitmap bm = BitmapFactory.decodeFile(normalIcon);
                Bitmap bm = ImageLoaderUtil.getBitmapfromFilewithoutfixes(normalIcon, 1);
                bitmapList.add(bm);
            } else {
                Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), com.efounder.ospmobilelib.R.drawable.ic_blank);
                bitmapList.add(bm);
            }
            String selectdeIcon = ((StubObject) espMenuList.get(i)).getObject(SELECTEDICON, "").toString();
            selectdeIcon = ResFileManager.IMAGE_DIR + "/" + selectdeIcon;
            File file_press = new File(selectdeIcon);
            if (file_press.exists()) {
                Bitmap bm = BitmapFactory.decodeFile(selectdeIcon);
                bitmap_pressList.add(bm);
            } else {
                Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), com.efounder.ospmobilelib.R.drawable.ic_blank);
                bitmap_pressList.add(bm);
            }

            //获取大图标的位置
            String size = soObject.getObject("size", "").toString();
            if ("larger".equals(size)) {
                largePosition = i;
                hasLargerImange = true;
            }


        }
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        Display dp = wm.getDefaultDisplay();
        mTabWidth = dp.getWidth();
        mTabCount = espMenuList.size();
        Log.i(TAG, "espMenuList.size()" + espMenuList.size());
        if (mTabCount > 0 && mTabCount < MAX_BOTTOM_ITEMS) {
            BOTTOM_ITEM = mTabCount;

            mCurrentTabIndex = 0;
            if (hasLargerImange) {
                mTabWidth = (mTabWidth - 16) / mTabCount;
            } else {
                mTabWidth = mTabWidth / mTabCount; // 计算每个tab的宽度
            }

        } else {
            mTabWidth = mTabWidth / MAX_BOTTOM_ITEM; // 计算每个tab的宽度
            mCurrentTabIndex = 0;
        }
        LayoutParams outParams = new LayoutParams(mTabWidth,
                LayoutParams.WRAP_CONTENT);
        outParams.gravity = Gravity.CENTER;
        OnClickListener clkListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                int index = (Integer) v.getTag();
                Log.v("index", "index:" + index);
                if (index != mCurrentTabIndex) {
                    if (mTabChangedListener != null)
                        mTabChangedListener.onCurrentTabChanged(index);
                    mCurrentTabIndex = index;
                    setCurrentTabColor(index);
                } else if (index == mCurrentTabIndex) {
                    //todo 再次点击同一菜单，发送事件 让某些界面滚动到最上方
                    EventBus.getDefault().post(new TabMenuClickEvent(index, espMenuList.get(index)));
                }

                //TODO 检查授权
//				checkAuthorization();
            }
        };
        //添加一个线条
        ImageView line = new ImageView(mContext);
        line.setBackgroundColor(getResources().getColor(com.efounder.ospmobilelib.R.color.tabline));
        LayoutParams lineParams = new LayoutParams(LayoutParams.FILL_PARENT,
                1);
        this.addView(line, lineParams);
        LinearLayout tabcontent = new LinearLayout(mContext);
        tabcontent.setOrientation(LinearLayout.HORIZONTAL);
        LayoutParams tabcontentParams = new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        tabcontent.setLayoutParams(tabcontentParams);
//        this.setBackgroundResource(R.color.tabbar_background_color);
//        this.setBackgroundColor(context.getResources().getColor(R.color.tabbar_background_color));
        this.setBackgroundColor(JfResourceUtil.getSkinColor(R.color.tabbar_background_color));
        this.addView(tabcontent);
        //逐个添加Tab
        if (mTabCount < MAX_BOTTOM_ITEMS) {
            addItemTab(outParams, clkListener, tabcontent, mTabCount);
        } else {
            addItemTab(outParams, clkListener, tabcontent, BOTTOM_ITEM);
            LinearLayout tab = new LinearLayout(mContext);
            tab.setGravity(Gravity.CENTER);
            tab.setOrientation(LinearLayout.VERTICAL);
            tab.setPadding(0, 5, 0, 5);
//			tab.setTag(MORE_BTN); // 设置内部标号
            tab.setTag(mTabCount); // 设置内部标号
            tab.setClickable(true);
            EFImage imv = new EFImage(mContext);
            imv.setScaleType(ScaleType.FIT_CENTER);
            imv.setBackgroundResource(R.drawable.button_selector_menu_more);
//			imv.setImageBitmap(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_menu_more_n));
            imageList.add(imv);
            TextView tv = new TextView(mContext);
            tv.setGravity(Gravity.CENTER_HORIZONTAL);
            tv.setText(R.string.mail_more);
            tv.setTextColor(JfResourceUtil.getSkinColor(R.color.tabbar_text_normal_color));
            textList.add(tv);
            DisplayMetrics dm = getResources().getDisplayMetrics();
//            System.out.println("屏幕宽度" + dm.widthPixels + "  屏幕高度" + dm.heightPixels);
            int ivWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 42, getResources().getDisplayMetrics());
            int ivHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, getResources().getDisplayMetrics());
            tab.addView(imv, ivWidth, ivHeight);
            tab.addView(tv);

            tab.setOnClickListener(clkListener);
            tabcontent.addView(tab, outParams);
            initQuickActionGrid();

            menuListTemp = new ArrayList<Object>();
            for (int i = BOTTOM_ITEM; i < this.mTabCount; i++) {
                menuListTemp.add(espMenuList.get(i));
            }
        }

    }

    /**
     * 检查授权
     */
    private void checkAuthorization() {
        clickCount++;
        if (clickCount % 3 == 0 && EnvironmentVariable.getProperty("authorization").equals("FALSE")) {
            Toast.makeText(getContext(), R.string.mail_trail_edition_grant, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 初始化快捷栏  list剩余菜单选项  底部菜单超过6项时调用该方法
     */
    private void initQuickActionGrid() {
        mGrid = new QuickActionGrid(mContext);
        for (int i = BOTTOM_ITEM; i < this.mTabCount; i++) {
            mGrid.addQuickAction(new QuickAction(new BitmapDrawable(mContext.getResources(), bitmapList.get(i)), ((StubObject) espMenuList.get(i)).getObject(CAPTION, ResStringUtil.getString(R.string.mail_unknown)).toString()));
        }
        mGrid.setOnQuickActionClickListener(mActionListener);
    }

    /**
     * 快捷栏item点击事件
     */
    private QuickActionWidget.OnQuickActionClickListener mActionListener = new QuickActionWidget.OnQuickActionClickListener() {
        public void onQuickActionClicked(QuickActionWidget widget, int position) {
            if (mTabChangedListener != null) {
                mTabChangedListener.onCurrentTabChanged(BOTTOM_ITEM + position);
//					AbLogUtil.i(TAG, "BOTTOM_ITEM+position:"+(BOTTOM_ITEM+position));
                mCurrentTabIndex = (BOTTOM_ITEM + position);
                setCurrentTabColor(BOTTOM_ITEM + position);
            }
        }
    };

    private Drawable tintDrawable(Drawable drawable, int colors) {
        final Drawable wrappedDrawable = DrawableCompat.wrap(drawable).mutate();
        DrawableCompat.setTint(wrappedDrawable, colors);
        return wrappedDrawable;
    }

    /**
     * 添加底部ItemTab选项
     *
     * @param outParams
     * @param clkListener
     * @param tabcontent
     * @param mTabCount
     */
    private void addItemTab(LayoutParams outParams,
                            OnClickListener clkListener, LinearLayout tabcontent, int mTabCount) {
        for (int i = 0; i < mTabCount; ++i) {
            LinearLayout tab = new LinearLayout(mContext);
            tab.setGravity(Gravity.CENTER);
            tab.setOrientation(LinearLayout.VERTICAL);
            tab.setPadding(0, 5, 0, 2);
            tab.setTag(i); // 设置内部标号
            tab.setClickable(true);
            EFImage imv = new EFImage(mContext);
            imv.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imv.setImageBitmap(bitmapList.get(i));
            if (0 == i) {
                Drawable drawable = new BitmapDrawable(bitmap_pressList.get(0));
                drawable = tintDrawable(drawable, JfResourceUtil.getSkinColor(R.color.tabbar_icon_select_color));
                imv.setImageDrawable(drawable);
                //imv.setImageBitmap(bitmap_pressList.get(0));
            }


            imageList.add(imv);
            TextView tv = new TextView(mContext);
            tv.setGravity(Gravity.CENTER_HORIZONTAL);
            String caption = ((StubObject) espMenuList.get(i)).getObject(CAPTION, "").toString();
            tv.setText(caption);
            if (0 == i) {
                tv.setTextColor(JfResourceUtil.getSkinColor(R.color.tabbar_text_select_color));
            } else {
                tv.setTextColor(JfResourceUtil.getSkinColor(R.color.tabbar_text_normal_color));
            }
            textList.add(tv);
            DisplayMetrics dm = getResources().getDisplayMetrics();
//            System.out.println("屏幕宽度" + dm.widthPixels + "  屏幕高度" + dm.heightPixels);
            int ivWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, getResources().getDisplayMetrics());
            int ivHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, getResources().getDisplayMetrics());
            if (hasLargerImange && i == largePosition) {
                imv.setScaleType(ImageView.ScaleType.FIT_XY);
                tab.addView(imv, ivWidth + 28, ivHeight + 28);
            } else {
                tab.addView(imv, ivWidth * 2, ivHeight);
                tv.setTextSize(12);
                tab.addView(tv);

            }

//			BadgeView badgeView = new BadgeView(mContext, imv);
//			badgeView.setBadgeMargin(0, 0);
//			badgeView.setTextSize(13);
//			badgeView.setTag("badge" + i);

            tab.setOnClickListener(clkListener);
            if (hasLargerImange && i == largePosition) {
                LayoutParams outParams1 = new LayoutParams(mTabWidth + 16,
                        LayoutParams.WRAP_CONTENT);
                outParams1.gravity = Gravity.CENTER;
                tabcontent.addView(tab, outParams1);
            } else {
                tabcontent.addView(tab, outParams);

            }
        }
    }

    /**
     * 点击标签后更改所有的标签状态
     *
     * @param index
     */
    public void setCurrentTabColor(int index) {
        for (int i = 0; i < BOTTOM_ITEM; i++) {
            if (index == i) {
                Drawable drawable = new BitmapDrawable(bitmap_pressList.get(i));
                drawable = tintDrawable(drawable, JfResourceUtil.getSkinColor(R.color.tabbar_icon_select_color));
                imageList.get(i).setImageDrawable(drawable);
                //imageList.get(i).setImageBitmap(bitmap_pressList.get(i));
                textList.get(i).setTextColor(JfResourceUtil.getSkinColor(R.color.tabbar_text_select_color));
            } else {
                imageList.get(i).setImageBitmap(bitmapList.get(i));
                textList.get(i).setTextColor(JfResourceUtil.getSkinColor(R.color.tabbar_text_normal_color));
            }
        }
    }

    /**
     * 设置当前Tab的序号
     *
     * @param index
     */
    public void setCurrentTab(int index) {
        if (index > -1 && index < mTabCount && index != mCurrentTabIndex) {
            mCurrentTabIndex = index;
            setCurrentTabColor(index);
            this.invalidate();
            if (mTabChangedListener != null)
                mTabChangedListener.onCurrentTabChanged(mCurrentTabIndex);
        }
    }

    public void setOnCurrentTabChangedListener(
            com.efounder.widget.TabBarNew.OnCurrentTabChangedListener listener) {
        mTabChangedListener = listener;
    }

    /**
     * 获取Tab个数
     *
     * @return Tab个数
     */
    public int getTabCount() {
        return mTabCount;
    }

    public interface OnCurrentTabChangedListener {
        public void onCurrentTabChanged(int index);
    }

    /**
     * 获取默认选中的tab页，从配置文件中配置，defaultDisplay字段
     *
     * @return
     */
    public int getDefaultSelectedTab() {
        int position = 0;
        String currentDisplay = EnvironmentVariable.getProperty("currentDisplayFrag","");

        for (int i = 0; i < espMenuList.size(); i++) {
            StubObject stubObject = espMenuList.get(i);
            Hashtable hashtable = stubObject.getStubTable();
            if(!currentDisplay.equals("")){
                String id = stubObject.getString("id","");
                if(id.equals(currentDisplay)) {
//					currentDisplayPos = i;
                    return i;
                }
            }else {
                if (hashtable.containsKey("defaultDisplay")) {
                    if ("true".equals(hashtable.get("defaultDisplay"))) {
                        position = i;
                    }

                }
            }
        }
        return position;
    }

    public List<EFImage> getImageList() {
        return imageList;
    }

    public void setImageList(List<EFImage> imageList) {
        this.imageList = imageList;
    }
}
